using System;
using System.Web.UI.WebControls;
using Sedna.Core.Controller;

namespace Sedna.Core.Controls.Grid
{
	public class GridTextBox: TextBox, IDataGridAwareControl
	{
		private IDataGridController controller;

		public IDataGridController Controller
		{
			set { controller = value; }
		}

		public GridTextBox(IConfiguration configuration) : base(configuration)
		{
			TextChanged += new EventHandler(OnTextChanged);
		}

		private void OnTextChanged(object sender, EventArgs e)
		{
			UpdateEntity();
		}

		private void UpdateEntity()
		{
            object entity = controller.GridSourceCache[(int)ViewState["entityIndex"]];
		    if (binder.Unbind(entity, "Text", base.Configuration.DataParser))
			{
			    /* if entity is non persistent it must be removed firstly, for avoid entry in the set two same entities */
                controller.TransientData.Remove(entity);
    			controller.TransientData.Add(entity);
			}
		}

		public void OnDataBinding(DataGridItem dataGridItem)
		{
			ViewState["entityIndex"] = dataGridItem.DataSetIndex;
            binder.Bind(dataGridItem.DataItem, "Text", base.Configuration.DataTranslator);
            binder.Bind(dataGridItem.DataItem, new string[] { "Enabled" });
		}



		protected override void Bind() 
		{
		}

		protected override void Unbind()
		{
		}

        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            if (controller.InvalidData != null && controller.InvalidData.Contains(controller.GridSourceCache[(int)ViewState["entityIndex"]]))
                CssClass = BorderStyle == BorderStyle.None ? "innertablecellinvalid" : "invalidinput";
            base.Render(writer);
        }
	}
}
